import { formatSeconds } from '@/utils/format';
import { Card } from 'antd';
import ReactECharts from 'echarts-for-react';
import { useEffect, useRef } from 'react';

const LineChartHour = ({ data = [], open }) => {
  const chartRef = useRef(null);

  useEffect(() => {
    if (!chartRef.current || !open) return;

    const container = chartRef.current.ele; // 获取图表容器 DOM
    const observer = new ResizeObserver(() => {
      chartRef.current?.getEchartsInstance()?.resize();
    });

    observer.observe(container);
    return () => observer.disconnect(); // 清理监听
  }, [open]); // 依赖 Modal 的打开状态

  // 处理数据，提取hour和duration字段
  const xAxisData = data?.map((item) => `${item.hour}:00`) || [];
  const durationData = data?.map((item) => item.duration / 60) || []; // 转换为分钟

  // 图表配置
  const option = {
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let result = `${params[0].name}<br/>`;
        params.forEach((param) => {
          if (param.seriesName === '趟次数') {
            result += `${param.seriesName}: ${param.value}<br/>`;
          } else {
            result += `${param.seriesName}: ${formatSeconds(
              param.value * 60,
            )}<br/>`;
          }
        });
        return result;
      },
    },
    grid: {
      top: '15%',
      left: '3%',
      right: '40px',
      bottom: '3%',
      containLabel: true,
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: xAxisData,
      name: '小时',
    },
    yAxis: [
      {
        type: 'value',
        name: '时长(分钟)',
        position: 'left',
      },
      {
        type: 'value',
        name: '趟次数',
        position: 'right',
      },
    ],
    legend: {
      data: ['时长'],
      top: '5px',
    },
    series: [
      {
        name: '时长',
        type: 'line',
        data: durationData,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#52c41a',
        },
        lineStyle: {
          width: 3,
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: 'rgba(82,196,26,0.3)',
              },
              {
                offset: 1,
                color: 'rgba(82,196,26,0.1)',
              },
            ],
          },
        },
      },
    ],
  };

  return (
    <Card style={{ marginBottom: 16 }}>
      <ReactECharts
        ref={chartRef}
        option={option}
        style={{ height: '300px', width: '100%' }}
        opts={{ renderer: 'svg' }}
      />
    </Card>
  );
};

export default LineChartHour;
